package com.wjw;

import com.wjw.model.User;
import com.wjw.utils.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class test {

    @Test
    public void test1(){
        //读取hibernate配置文件
        Configuration configuration=new Configuration().configure();
        //创建SessionFactory工厂对象
        SessionFactory sessionFactory=configuration.buildSessionFactory();
        //创建session对象 和网页servlet的session无关
        Session session=sessionFactory.openSession();   //openSession必须关闭session资源 否则会浪费
        //开启事务
        Transaction transaction=session.beginTransaction();
        //持久化操作
        User user=new User(1,"xiaoming","daomei");
        session.save(user);
        try {
            transaction.commit();
        }catch (Exception e){
            e.printStackTrace();
            transaction.rollback();
        }finally {
            if (null!=session){
                session.close();
            }
        }

    }

    @Test
    public void testAdd(){
        Session session= HibernateUtil.getSession();
        User user=new User("小红","倒霉啊");
        Transaction transaction=session.beginTransaction();
        try {
            session.save(user);
            transaction.commit();
        }catch (Exception e){
            e.printStackTrace();
            transaction.rollback();
        }finally {
            HibernateUtil.closeSession(session);
        }
    }

    @Test
    public void testSearch(){
        Session session=HibernateUtil.getSession();
        //get直接查 load懒加载 用到的时候才会查
        User user=(User)session.load(User.class,2);
        System.out.println(user.getName());
        HibernateUtil.getSession();
    }

    @Test
    public void testDel(){
        Session session=HibernateUtil.getSession();
        Transaction transaction=session.beginTransaction();
        try {
            //先查才能删
            User user=(User)session.get(User.class,2);
            session.delete(user);
            transaction.commit();
        }catch (Exception e){
            e.printStackTrace();
            transaction.rollback();
        }finally {
            HibernateUtil.closeSession(session);
        }

    }

    @Test
    public void testUpdate(){
        Session session=HibernateUtil.getSession();
        Transaction transaction=session.beginTransaction();
        try {
            //先查再改， 也可以不查直接new对象
            User user=(User)session.get(User.class,2);
            user.setNumber("唉唉唉倒霉啊");
            session.update(user);
            transaction.commit();
        }catch (Exception e){
            e.printStackTrace();
            transaction.rollback();
        }finally {
            HibernateUtil.closeSession(session);
        }
    }
}
